﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace AlertListener
{
    public class AlertListener
    {
        private static readonly int ID_GUI = 14;

        private TcpClient tcpclnt;
        private static Thread listenThread = null;
      
        private string ServerIP ;
        private string ServerPort ;

        public AlertListener(string ServerIP, string ServerPort) 
        {
            this.ServerIP = ServerIP;
            this.ServerPort = ServerPort;
        }

        public void Start()
        {
            if (listenThread == null)
            {
                listenThread = new Thread(new ThreadStart(Connect));
                listenThread.Name = "AlertListener";
                listenThread.Start();
            }
        }

        public void Stop()
        {
            if (tcpclnt != null)
            {
                tcpclnt.Close();
                tcpclnt = null;
            }

            if (listenThread != null)
            {
                listenThread.Abort();
                listenThread = null;
            }
        }

        private void Connect()
        {
            // open server connection
            tcpclnt = new TcpClient();
            NetworkStream stream = null;

            try
            {
                Console.WriteLine("Connecting.....");
                tcpclnt.Connect(ServerIP, Int32.Parse(ServerPort));
                stream = tcpclnt.GetStream();
                Console.WriteLine("Connected");

                //************************************************
                // Now send autentification...
                //************************************************
                ASCIIEncoding asen = new ASCIIEncoding();

                byte[] buff = new byte[4096], tmp;
                string str = "MedicalDB";

                // lungime
                int len = asen.GetBytes(str).Length;
                tmp = BitConverter.GetBytes(len);
                for (int i = 0; i < 4; i++)
                    buff[i] = tmp[i];

                // id
                tmp = BitConverter.GetBytes(ID_GUI);
                for (int i = 0; i < 4; i++)
                    buff[4 + i] = tmp[i];

                // data
                tmp = asen.GetBytes(str);
                for (int i = 0; i < len; i++)
                    buff[8 + i] = tmp[i];

                // transmitere
                stream.Write(buff, 0, 8 + len);
            }
            catch (Exception x)
            {
                Console.WriteLine("Exception has occured in AlertListener1"+x);

                if (tcpclnt != null)
                {
                    tcpclnt.Close();
                    tcpclnt = null;
                }

                if (listenThread != null)
                {
                    listenThread.Abort();
                    listenThread = null;
                }
                
                return;
            }

            //************************************************
            // Now start listening for alerts...
            //************************************************
            // Connection buffers...
            int bytesRead, dataLen;
            int sensorID;
            byte[] rawData = new byte[4096];

            string CNP = "";
            string Msg = "";

            while (true)
            {
                bytesRead = 0;

                try
                {
                    // Blocks until server sends an alert...
                    if ((bytesRead = stream.Read(rawData, 0, 4)) != 4)
                        throw new Exception();

                    // Get Length
                    dataLen = BitConverter.ToInt32(rawData, 0);

                    // Get the rest of data
                    if (dataLen > 0 &&
                         (bytesRead = stream.Read(rawData, 0, dataLen)) != dataLen)
                        throw new Exception();

                    // Get CNP
                    for (int i = 0; i < 13; i++)
                    {
                        CNP += (char)rawData[i];
                    }

                    // Get IdSenzor
                    sensorID = BitConverter.ToInt32(rawData, 13);

                    // Get Msg
                    for (int i = 0; i < dataLen - 4 - 13; i++)
                    {
                        Msg += (char)rawData[i + 13 + 4];
                    }

                    //
                    // Now show the message
                    //
                    System.Console.Beep();
                    MessageBox.Show("Pacientul " + CNP + " are: " + Msg,
                                    "Alerta",
                                    MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    // Clean data...
                    CNP = "";
                    Msg = "";
                }
                catch (Exception x)
                {
                    Console.WriteLine("Exception has occured in AlertListener2"+x);

                    if (tcpclnt != null)
                    {
                        tcpclnt.Close();
                        tcpclnt = null;
                    }

                    if (listenThread != null)
                    {
                        listenThread.Abort();
                        listenThread = null;
                    }

                    return;
                }
            }
        }
    }
}
